// pages/detail.js
const config = require('../../utils/config.js')

const util = require('../../utils/util.js')
import _ from './../../utils/lodash.js';
//获取应用实例
// var QQMapWX = require('../../libs/qqmap-wx-jssdk.js');
//
// var qqmapsdk = new QQMapWX({
//   key: 'UDUBZ-OZQ3F-IGWJH-JVQLK-SI5J2-UPFAU' //在这里输入你在腾讯位置服务平台申请的KEY
// });
const find = _.find;
const app = getApp();
function isNumericStart(str) {
  return /^\d/.test(str);
}
let EBOriginData = '';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    user_id: app.globalData.userInfo ? app.globalData.userInfo.id : '',
    concentrator_detail:{},
    id: '',
    name: '',
    number: '',
    remark:'',
    imei:'',
    logs:[],
    latitude: 42.92736760935551,
    longitude: 89.19229343394916,
    address: '',
    markers: [{
      id: 1,
      latitude: 42.92736760935551,
      longitude: 89.19229343394916,
      width: '30', // 标记点图标宽度
      height: '60' // 标记点图标高度
    }],
    port:0,
    progress:0,
    portArr:[],
    post1CaliberIndex: 0,
    post2CaliberIndex: 0,
    post3CaliberIndex: 0,
    post4CaliberIndex: 0,
    post5CaliberIndex: 0,
    post6CaliberIndex: 0,
    post7CaliberIndex: 0,
    post8CaliberIndex: 0,
    postCaliberArray: ['DN15', 'DN20', 'DN25', 'DN32', 'DN40', 'DN50', 'DN65', 'DN80', 'DN100', 'DN150', 'DN200', 'DN300'],
    port1:'',
    concentratorPicArr: [],
    port1PicArr: [],
    port2PicArr:[],
    port3PicArr:[],
    port4PicArr:[],
    port5PicArr:[],
    port6PicArr:[],
    port7PicArr:[],
    port8PicArr:[],
    item: {},
    online_status: '',
    logined_at: '',
    device_info: {},
    display_value_1:'',
    display_value_2:'',
    display_value_3:'',
    display_value_4:'',
    display_value_5:'',
    display_value_6:'',
    display_value_7:'',
    display_value_8:'',
    pay_value_1:'',
    pay_value_2:'',
    pay_value_3:'',
    pay_value_4:'',
    pay_value_5:'',
    pay_value_6:'',
    pay_value_7:'',
    pay_value_8:'',
    paymentData: [],
    showComplete: true,
    uploadImg: [],
    all_departments: [],
    all_staffs: [],
    department: '',
    staff: '',
    deviceId:'',
    editable:false,
    connected:false,
    swapStep:1,
    resetSuccess:false,

  },
  timer: null,
  powerDrawer: function (e) {
    var currentStatu = e.currentTarget.dataset.statu;
    this.util(currentStatu)
  },
  util: function (currentStatu) {
    /* 动画部分 */
    // 第1步：创建动画实例 
    var animation = wx.createAnimation({
      duration: 200, //动画时长
      timingFunction: "linear", //线性
      delay: 0 //0则不延迟
    });

    // 第2步：这个动画实例赋给当前的动画实例
    this.animation = animation;

    // 第3步：执行第一组动画：Y轴偏移240px后(盒子高度是240px)，停
    animation.translateX(wx.getSystemInfoSync().windowWidth).step();

    // 第4步：导出动画对象赋给数据对象储存
    this.setData({
      animationData: animation.export()
    })

    // 第5步：设置定时器到指定时候后，执行第二组动画
    setTimeout(function () {
      // 执行第二组动画：Y轴不偏移，停
      animation.translateX(0).step()
      // 给数据对象储存的第一组动画，更替为执行完第二组动画的动画对象
      this.setData({
        animationData: animation
      })

      //关闭抽屉
      if (currentStatu == "close") {
        this.setData({
          showModalStatus: false
        });
      }
    }.bind(this), 200)

    // 显示抽屉
    if (currentStatu == "open") {
      this.setData({
        showModalStatus: true
      });
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options);
    const that = this;
    this.setData({
      portArr:[Number(options.port)]
    },function (){
      for(let i=1;i<=this.data.portArr.length;i++){
        this.setData({
          [`port${i}Origin`]:''
        })
      }
      this.setData({
        editable:true,
        port: options.port,
        deviceId:options.deviceId,
        address:options.address,
        number: options.number,
        type: options.type,
        [`portOld${options.port}`]:options.meter_number,
        connected:Boolean(options.connected==='true')
      },function (){
        // if(this.data.type==='add'||this.data.type==='del'){
        //   this.fetConctrator();
        // }
        this.fetConctrator()
        this.getBLEDeviceServices(that.data.deviceId);
      })
    })
    if(options.type==='add'){
      wx.setNavigationBarTitle({
        title:`${options.number}端口${options.port}添加水表`,
      })
    }else if(options.type==='del'){
      wx.setNavigationBarTitle({
        title:`${options.number}端口${options.port}删除水表`,
      })
    }else if(options.type==='swap'){
      wx.setNavigationBarTitle({
        title:`${options.number}端口${options.port}换表`,
      })
    }else if(options.type==='reset'){
      wx.setNavigationBarTitle({
        title:`${options.number}端口${options.port}重置水表`,
      })
    }else if(options.type==='sync'){
      wx.setNavigationBarTitle({
        title:`${options.number}端口${options.port}同步表盘`,
      })
    }

    wx.onBLEConnectionStateChange(function (res) {
      // 该方法回调中可以用于处理连接意外断开等异常情况
      console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`)
      that.setData({
        connected: res.connected
      }, function () {
        if (res.connected) {
          this.getBLEDeviceServices(that.data.deviceId)
        } else {
          util.toastError('蓝牙连接已断开')
        }
      })
    })

    // this.getLocation()

    // this.getInfo(true);



  },
  getBLEDeviceServices(deviceId) {
    console.log('getBLEDeviceServices')
    const that = this
    wx.getBLEDeviceServices({
      deviceId: this.data.deviceId,
      success: (res) => {
        console.log('所有服务', res.services)
        let serviceIds = [];
        for (let i = 0; i < res.services.length; i++) {

          //安卓上，部分机型获取设备服务时会多出 00001800 和 00001801 UUID 的服务，这是系统行为，注意不要使用这两个服务。
          if (res.services[i].uuid.indexOf('00001800') >= 0 || res.services[i].uuid.indexOf('00001801') >= 0) {
            console.log(`res.services[i].uuid ${res.services[i].uuid} 是系统行为，不要使用`)
          } else {
            console.log('res.services[i].uuid', res.services[i].uuid)
            serviceIds.push(res.services[i].uuid)

          }

        }
        this.setData({
          serviceIds: serviceIds
        }, function () {
          for (let i = 0; i < this.data.serviceIds.length; i++) {
            setTimeout(function () {
              that.getBLEDeviceCharacteristics(deviceId, that.data.serviceIds[i])
            }, 100)

          }
        })
      }
    })
  },

  getBLEDeviceCharacteristics(deviceId, serviceId) {
    const that=this;
    wx.getBLEDeviceCharacteristics({
      deviceId,
      serviceId,
      success: (res) => {
        console.log('getBLEDeviceCharacteristics success', res.characteristics)
        let findWrite = find(res.characteristics, function (o) {
          return o.properties.write
        })
        let findNotify = find(res.characteristics, function (o) {
          return o.properties.notify
        })


        if (findWrite && findNotify) {

          this.setData({
            selectServerChars: {
              deviceId: deviceId,
              serviceId: serviceId,
              writeCharUUID: findWrite.uuid,
              notifyCharUUID: findNotify.uuid,
            }
          }, function () {
            this.recvBLECharacterNotice(deviceId, serviceId, this.data.selectServerChars.notifyCharUUID);
            this.writeLogs(`发现服务`)




            // if((this.data.type!=='reset')&&(this.data.type!=='swap')){
            //   this.handleSendE0()
            // }
            if(this.data.type==='reset'||this.data.type==='swap'||this.data.type==='sync'){
              setTimeout(function (){
                console.log('获取当前表盘数')
                that.handleSendEB()
              },1000)
            }

          })

        }


      },
      fail(res) {
        console.log('serviceId 出错了', serviceId)
        console.error('getBLEDeviceCharacteristics', res)
        util.bleErrCode(res.errCode);
        that.writeLogs(util.bleErrCode(res.errCode), 'red')
      }
    })
    //监听蓝牙低功耗设备的特征值变化事件。必须先调用 wx.notifyBLECharacteristicValueChange 接口才能接收到设备推送的 notification。
    wx.onBLECharacteristicValueChange((characteristic) => {
      console.log(characteristic.value)

    })
  },
  getName: function (name) {
    let n1 = name.substr(0, 2)
    let n2 = name.substr(2, 2)
    let n3 = name.substr(4, 2)
    let n4 = name.substr(6, 2)
    return `${n4} ${n3} ${n2} ${n1}`
  },
  handleSendE6: function (port) {//清零
    let str = `0E ${this.getName(this.data.number)} 00 E6 ${port}`
    let sendHex = '68 ' + str + ' ' + util.calc(str) + ' 16'
    console.log('sendHex', sendHex)
    this.writeLogs(`下发数据：${sendHex}`, 'orange');
    this.writeBLECharacteristicValue(sendHex)
  },
  handleSendEB: function () {//读表数据
    console.log('this.getName()',this.getName(this.data.number))
    let str = `0E ${this.getName(this.data.number)} 00 EB`
    let sendHex = '68 ' + str + ' ' + util.calc(str) + ' 16'
    console.log('sendHex', sendHex)
    this.writeLogs(`下发数据：${sendHex}`, 'orange');
    this.writeBLECharacteristicValue(sendHex)
  },
  handleSend85: function (port,value) {//设置表底数
    if(!(this.data[(this.data.type==='reset'||this.data.type==='sync')?`display_value_${Number(port)}`:`port${Number(port)}Origin`].toString())){
      util.toastError(`表盘数为空,请重新进入获取表盘数`)
      return false
    }
    let input1 = util.padWithZeros(parseInt(Number(this.data[(this.data.type==='reset'||this.data.type==='sync')?`display_value_${Number(port)}`:`port${Number(port)}Origin`]) * 1000), 8, '0')
    console.log('input1', input1)
    let str = `0E ${this.getName(this.data.number)} 00 85 0${port} ${input1.substr(6, 2)} ${input1.substr(4, 2)} ${input1.substr(2, 2)} ${input1.substr(0, 2)} 2C`

    let sendHex = '68 ' + str + ' ' + util.calc(str) + ' 16'
    console.log('sendHex', sendHex)
    this.writeLogs(`下发数据：${sendHex}`, 'orange');
    this.writeBLECharacteristicValue(sendHex)
  },
  decToHex:function(number){
    return (parseInt(number,10)>>>0).toString(16).toLocaleUpperCase();
  },
  handleSend86: function (port,value) {//设置充值水量
    let input1 = this.data[`pay_value_${Number(port)}`]

    let str=''
    let input2 = '0001'
    // if(Number(input1)===0){
    //   console.log('需下发充值水量为0，不下发指令')
    //   util.toastError('需下发充值水量为0，不下发指令');
    //   this.writeLogs(`需下发充值水量为0，不下发指令`, 'orange');
    //   this.setPsn(0,this.handleSendE0)
    //   return
    // }
    if(Number(input1)>=0){
      console.log('大于0')
      input1 = util.padWithZeros(parseInt(Number(Math.round(input1 * 1000) / 1000) * 1000).toString(16), 8, '0')
      console.log('input1',input1)
      str = `0E ${this.getName(this.data.number)} 00 86 0${port} ${input1.substr(6, 2)} ${input1.substr(4, 2)} ${input1.substr(2, 2)} ${input1.substr(0, 2)} ${input2.substr(2, 2)} ${input2.substr(0, 2)} 00 00`

    }else if(Number(input1)<0){
      console.log('用水量',Number(input1))
      console.log('小于0')
      input1 = this.decToHex(Number(Math.round(input1 * 1000) / 1000) * 1000)
      console.log('input1',input1)
      str = `0E ${this.getName(this.data.number)} 00 86 0${port} ${input1.substr(6, 2)} ${input1.substr(4, 2)} ${input1.substr(2, 2)} ${input1.substr(0, 2)} ${input2.substr(2, 2)} ${input2.substr(0, 2)} 00 00`

    }


    let sendHex = '68 ' + str + ' ' + util.calc(str) + ' 16'
    console.log('sendHex', sendHex)
    this.writeLogs(`下发数据：${sendHex}`, 'orange');
    this.writeBLECharacteristicValue(sendHex)
  },
  handleSendE0: function () {//请求上线

    let str = `0E ${this.getName(this.data.number)} 00 E0`
    let sendHex = '68 ' + str + ' ' + util.calc(str) + ' 16'
    console.log('sendHex', sendHex)
    this.writeLogs(`下发数据：${sendHex}`, 'orange');
    this.writeBLECharacteristicValue(sendHex)
  },
  writeBLECharacteristicValue(sendHex) {
    const that = this
    if(!this.data.selectServerChars){
      util.toastError('出现未知错误，请返回首页重新扫码');
      return false
    }
    if (!this.data.connected) {
      util.toastError('请先连接设备');
      return false
    }
    var typedArray = new Uint8Array(sendHex.match(/[\dA-F]{2}/gi).map(function (h) {
      return parseInt(h, 16)
    }))
    // console.log(typedArray)

    var writeValue = typedArray.buffer
    wx.writeBLECharacteristicValue({
      deviceId: this.data.selectServerChars.deviceId,
      serviceId: this.data.selectServerChars.serviceId,
      characteristicId: this.data.selectServerChars.writeCharUUID,
      value: writeValue,
      success(res) {
        // that.writeLogs("下发数据成功: " + sendHex, 'green');
      },
      fail: function (res) {
        console.log(res);
        that.writeLogs("下发数据失败: " + res.errCode, 'red');
        util.bleErrCode(res.errCode);
      }
    })
  },

  recvBLECharacterNotice: function (deviceId, serviceId, charId) {
    //接收设置是否成功
    this.writeLogs("注册Notify服务");
    var that = this;
    wx.notifyBLECharacteristicValueChange({
      deviceId: deviceId,
      serviceId: serviceId,
      characteristicId: charId,
      state: true, //启用Notify功能
      success: function (res) {
        wx.onBLECharacteristicValueChange(function (res) {
          console.log(res);
          let notifyData = util.ab2hex(res.value)
          console.log('notifyData', notifyData)
          if (notifyData.substr(14, 2) === 'e0'){
            if(notifyData.substr(16, 2)==='00'){
              // util.toastError(`请求上线成功`)
              that.writeLogs(`请求上线指令下发成功`, 'green');
              if(that.data.type==='add'){
                wx.hideLoading()
                util.toastError(`加表成功`);
                that.writeLogs(`加表成功`, 'green');
              }
              if(that.data.type==='del'){
                wx.hideLoading()
                util.toastError(`删表成功`);
                that.writeLogs(`删表成功`, 'green');
              }
              if(that.data.type==='swap'&&that.data.swapStep===1){
                //获取系统充值水量
                setTimeout(function (){
                  that.fetConctratorValue()
                },30000)
              }

              if(that.data.type==='swap'&&that.data.swapStep===3){
                wx.hideLoading()
                util.toastError(`换表成功`);
                that.writeLogs(`换表成功`, 'green');
              }
              if(that.data.type==='reset'){

                if(!that.data.resetSuccess){
                  setTimeout(function (){
                    that.fetConctratorValue()
                  },15000)
                }else {
                  wx.hideLoading()
                  util.toastError(`重置表成功`);
                  that.writeLogs(`重置表成功`, 'green');
                  that.setData({
                    resetSuccess:false
                  })
                }


              }
              if(that.data.type==='sync'){
                wx.hideLoading()
                that.writeLogs(`机电同步成功`, 'green');
                util.toastError(`请检查平台显示是否正确`);
              }
            }else{
              wx.hideLoading()
              wx.showToast({
                title: '上线失败',
                icon: 'error',
                duration: 2000
              })
              that.writeLogs(`请求上线指令下发失败`, 'red');
            }


          }

          if (notifyData.substr(14, 2) === '85'){
            if(that.data.type==='add'){
              if(notifyData.substr(16, 2)==='00'){
                // util.toastError(`端口${that.data.port}设表盘数指令下发完成`)
                that.writeLogs(`端口${that.data.port}设表盘数指令下发成功`, 'green');
                setTimeout(function (){
                  that.handleSendE0();
                },10000)

                that.handleOk(0)
              }else{
                util.toastError('设表盘数指令下发失败')
                that.writeLogs(`端口${that.data.port}设表盘数指令下发失败`, 'red');
              }

            }
            if(that.data.type==='swap'){
              if(notifyData.substr(16, 2)==='00'){
                that.writeLogs(`端口${that.data.port}设表盘数指令下发成功`, 'green');
                setTimeout(function (){
                  that.handleOk(0)
                },3000)


              }else{
                util.toastError('设表盘数指令下发失败')
                that.writeLogs(`端口${that.data.port}设表盘数指令下发失败`, 'red');
              }

            }

            if(that.data.type==='reset'){
              if(notifyData.substr(16, 2)==='00'){
                that.writeLogs(`端口${that.data.port}设表盘数指令下发成功`, 'green');
                setTimeout(function (){
                  //修改系统集中器水表底数
                  that.editConctrator()
                },5000)
                setTimeout(function (){
                  that.handleSend86(that.data.port)//将下发充值放到设置表底数后面
                },30000)


              }else{
                util.toastError('设表盘数指令下发失败')
                that.writeLogs(`端口${that.data.port}设表盘数指令下发失败`, 'red');
              }

            }

            if(that.data.type==='sync'){
              if(notifyData.substr(16, 2)==='00'){
                that.writeLogs(`端口${that.data.port}设表盘数指令下发成功`, 'green');
                setTimeout(function (){
                  that.handleSendE0()
                },5000)


              }else{
                util.toastError('设表盘数指令下发失败')
                that.writeLogs(`端口${that.data.port}设表盘数指令下发失败`, 'red');
              }

            }
          }



          if (notifyData.substr(14, 2) === 'e6') {
            if(notifyData.substr(16, 2)==='00'){
              that.writeLogs(`端口${that.data.port}清零指令下发成功`, 'green');
              that.setData({
                progress:10,
              })
              if(that.data.type==='add'){
                setTimeout(function (){
                  that.handleSend85(that.data.port)
                },10000)

              }else if(that.data.type==='swap'){
                setTimeout(function (){
                  that.handleSend85(that.data.port)
                },30000)
              }else if(that.data.type==='reset'){
                setTimeout(function (){

                  that.handleSend85(that.data.port)
                  //中间加一步设置表底数

                },30000)

              }else if(that.data.type==='del'){
                wx.request({
                  url: `${config.prefix}/concentrator_psn`,
                  header: {
                    Authorization: `Bearer ${app.globalData.userInfo.token}`
                  },
                  method: 'POST',
                  data:{
                    items:[{ meter_number:that.data[`port${Number(that.data.port)}`],psn:0}]

                  },
                  success: function (res) {
                    console.log('get res', res)
                    if (res.statusCode === 200) {
                      console.log('PSN设置为0成功')
                      that.writeLogs(`PSN设置为0成功`, 'green');
                      that.setData({
                        [`port${that.data.port}`]:''
                      },function (){
                        that.handleOk(0)
                      })
                    }else {
                      util.converErrorCodeToMsg(res);
                    }
                  }
                })

              }

            }
            /*that.setData({
              E6data: {
                d1: `${notifyData.substr(16, 2)}`,
              }
            })*/
          }

          if (notifyData.substr(14, 2)  === '86'){
            if(notifyData.substr(16, 2)==='00'){
              // util.toastError(`充值下发成功`)
              that.writeLogs(`端口${that.data.port}充值下发成功`, 'green');
              if(that.data.type==='swap'){
                that.setPsn(1,function (){
                  setTimeout(function (){
                    wx.hideLoading()
                    that.setData({
                      swapStep:3
                    })
                    util.toastError(`新表数据下发成功，请确认营收已换表`)
                  },2000)
                })
              }else{
                that.setPsn(1,that.handleSendE0)
              }

            }else{
              util.toastError(`端口${that.data.port}充值下发失败`)
              that.writeLogs(`端口${that.data.port}充值下发失败,失败代码为:${notifyData.substr(16, 2)}`, 'red');
            }

          }

          if ((that.data.type === 'reset'||that.data.type === 'swap'||that.data.type === 'sync')&&notifyData.substr(14, 2).toUpperCase() !== 'E0'&&notifyData.substr(14, 2).toUpperCase() !== '86'
              &&notifyData.substr(14, 2).toUpperCase() !== '85'&&notifyData.substr(14, 2).toUpperCase() !== 'E6') {
            console.log('notifyData.length', notifyData.length)
            if (EBOriginData.length < 610) {
              EBOriginData = EBOriginData + notifyData
            }
            if (EBOriginData.length === 610) {
              notifyData = EBOriginData
              console.log('610 notifyData',notifyData)
              that.writeLogs(`端口${that.data.port}获取表盘数成功`,"green");
              let portsArr = []
              for (let i = 0; i < 8; i++) {
                let display_value = Number(`${notifyData.substr(90 + 4 + i * 66, 2)}${notifyData.substr(88 + 4 + i * 66, 2)}${notifyData.substr(86 + 4 + i * 66, 2)}${notifyData.substr(84 + 4 + i * 66, 2)}`)/1000;
                console.log('display_value ', display_value)
                that.setData({
                  [`display_value_${i+1}`]:display_value
                })
              }

            }

          }

        });
      },
      fail: function (res) {
        console.log(res);
        that.writeLogs("接收数据失败: " + res.errCode, 'red');
        util.bleErrCode(res.errCode);
      }
    })
  },
  setPsn:function (psn,cb){
    const that=this
    wx.request({
      url: `${config.prefix}/concentrator_psn`,
      header: {
        Authorization: `Bearer ${app.globalData.userInfo.token}`
      },
      method: 'POST',
      data:{
        items:[{ meter_number:that.data[`port${Number(that.data.port)}`],psn:psn}]

      },
      success: function (res) {
        console.log('get res', res)
        if (res.statusCode === 200) {
          console.log(`设置PSN为${psn}成功`)
          that.writeLogs(`设置PSN为${psn}成功`, 'green');
          that.setData({
            resetSuccess:true,
          },function (){
            if(cb){
              setTimeout(function (){
                cb();
              },30000)
            }

          })
        }else {
          util.converErrorCodeToMsg(res)
        }
      }
    })
  },
  writeLogs(text, color) {
    var now = new Date();
    var hours = now.getHours();
    var minutes = now.getMinutes();
    var seconds = now.getSeconds();
    let logs = this.data.logs;
    logs.unshift({
      color: color ? color : '#000',
      text: text,
      time: util.formatNumber(hours) + ':' + util.formatNumber(minutes) + ':' + util.formatNumber(seconds)
    })
    this.setData({
      logs
    })
  },
  changeRemarkValue: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      remark:e.detail.value,
    })

  },

  bindPickerChangePostCaliber1: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      post1CaliberIndex: e.detail.value
    })
  },
  bindPickerChangePostCaliber2: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      post2CaliberIndex: e.detail.value
    })
  },
  bindPickerChangePostCaliber3: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      post3CaliberIndex: e.detail.value
    })
  },
  bindPickerChangePostCaliber4: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      post4CaliberIndex: e.detail.value
    })
  },
  bindPickerChangePostCaliber5: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      post5CaliberIndex: e.detail.value
    })
  },
  bindPickerChangePostCaliber6: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      post6CaliberIndex: e.detail.value
    })
  },
  bindPickerChangePostCaliber7: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      post7CaliberIndex: e.detail.value
    })
  },
  bindPickerChangePostCaliber8: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      post8CaliberIndex: e.detail.value
    })
  },
  deleteImg: function (e) {
    const that = this;
    const ds = e.currentTarget.dataset
    console.log(e.currentTarget.dataset.item)
    const item = ds.item
    const port = ds.port
    wx.showModal({
      title: '提示',
      content: '确定要删除吗?',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定');
          if(ds.port){
            console.log(that.data[`port${ds.port}PicArr`])
            let index;
            for (let i = 0; i < that.data[`port${ds.port}PicArr`].length; i++) {
              console.log(that.data[`port${ds.port}PicArr`][i])
              if (item === that.data[`port${ds.port}PicArr`][i]) {
                index = i;
                console.log(index)
                that.data[`port${ds.port}PicArr`].splice(index, 1)
                that.setData({
                  [`port${ds.port}PicArr`]: that.data[`port${ds.port}PicArr`]
                },function(){
                })
              }
            }
          }else{
            let index;
            for (let i = 0; i < that.data.concentratorPicArr.length; i++) {
              if (item === that.data.concentratorPicArr[i]) {
                index = i;
                console.log(index)
                that.data.concentratorPicArr.splice(index, 1)
                that.setData({
                  concentratorPicArr: that.data.concentratorPicArr
                },function(){
                })
              }
            }
          }



        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  },
  bindble:function (){
    console.log('bindble')
    this.openBluetoothAdapter()
  },
  openBluetoothAdapter() {
    //util.toastError('请先打开蓝牙');
    console.log('openBluetoothAdapter')
    if(this.data.bleName&&this.data.deviceId){
      console.log('已经连接过')
      const name = this.data.bleName.length>8?this.data.bleName.substr(0,8):this.data.bleName;
      wx.navigateTo({
        url: `/pages/items/items?deviceId=${this.data.deviceId}&name=${name}`
      })
      return
    }
    wx.openBluetoothAdapter({
      success: (res) => {
        console.log('openBluetoothAdapter success', res)
        this.startBluetoothDevicesDiscovery()
      },
      fail: (res) => {
        console.log('openBluetoothAdapter fail', res)
        util.toastError('请先打开蓝牙'+res.errCode);
        if (res.errCode === 10001) {
          console.log('请先打开蓝牙1') //当蓝牙开关未开启或手机不支持蓝牙时，会返回错误 (errCode=10001)。
          // util.toastError('10001');
          wx.onBluetoothAdapterStateChange(function (res) {
            console.log('onBluetoothAdapterStateChange', res)
            if (res.available) {
              this.startBluetoothDevicesDiscovery()
            }
          })
        }
      }
    })
  },
  startBluetoothDevicesDiscovery() {
    // if (this._discoveryStarted) {
    //   return
    // }
    // this._discoveryStarted = true
    wx.showLoading({
    	title: '蓝牙连接中...',
    })
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: true,
      success: (res) => {
        console.log('startBluetoothDevicesDiscovery success', res)
        this.onBluetoothDeviceFound()
      },
    })
  },
  onBluetoothDeviceFound() {
    const that=this
    wx.onBluetoothDeviceFound((res) => {
      res.devices.forEach(device => {
        if (!device.name && !device.localName) {
          return
        }
        if (!isNumericStart(device.name || device.localName)) {
          return
        }
        let bleName=device.name?device.name:device.localName;
        console.log('bleName',bleName)
        if(bleName.indexOf(that.data.number)>=0){
          this.stopBluetoothDevicesDiscovery()
          this.setData({
            bleName:bleName,
            deviceId:device.deviceId
          })
          wx.navigateTo({
            url: `/pages/items/items?deviceId=${device.deviceId}&name=${bleName}`
          })
        }


      })
    })
  },
  stopBluetoothDevicesDiscovery() {
    wx.stopBluetoothDevicesDiscovery()
    wx.hideLoading()
  },
  fetConctratorValue: function (department) {
    const that = this;
    const port=that.data.port
    if(!(that.data[`display_value_${Number(port)}`].toString())){
      util.toastError('表盘数为空，请重新进入获取表盘数')
      return;
    }
    wx.request({
      url: `${config.prefix}/concentrator_info`,
      header: {
        Authorization: `Bearer ${app.globalData.userInfo.token}`
      },
      method: 'GET',
      data: {
        number: that.data.number
        // number:452409124758
      },
      success: function (res) {
        console.log('get res', res)
        if (res.statusCode === 200) {
          let data = res.data.data
          console.log('data', data)
          let meter_config = data
          if (meter_config) {
            console.log('meter_config', meter_config)
            for (let i in meter_config) {
              let item = meter_config[i];
              let index = i.substr(4, 1)
              console.log('item',item)
              that.setData({
                [`initial_value_${index}`]: item.initial_value,
                [`total_value_${index}`]: item.cumulative_payment_volume,
              })
            }

            setTimeout(function (){
              //用户总充值水量 - （当前水表表盘数 - 旧表底数）
              let value = Number(that.data[`total_value_${Number(port)}`]) - (Number(that.data[`display_value_${Number(port)}`]) - Number(that.data[`initial_value_${Number(port)}`]))
              that.setData({
                [`pay_value_${Number(port)}`]: Number(Math.round(value * 1000) / 1000)
              }, function () {
                console.log(that.data)
                if(that.data.type==='reset'){
                  setTimeout(function (){
                    that.handleSendE6(`0${that.data.port}`)
                  },15000)
                }
                if(that.data.type==='swap'){
                  setTimeout(function (){
                    wx.hideLoading()
                  },2000)
                }

              })
            },1000)


          }


        }
      }
    })
  },
  handleNext2:function (){
    console.log('(this.data[`pay_value${this.data.port}`])',(this.data[`pay_value${this.data.port}`]))
    if(!(this.data[`pay_value_${this.data.port}`])&&!(this.data[`pay_value_${this.data.port}`].toString())){

      console.log('充值水量不能为空')
      util.toastError(`充值水量不能为空`);
      return false
    }
    this.setData({
      swapStep:2
    })
  },
  handleRemoteConfirm:function (){
    const that=this
    wx.showModal({
      title: '提示',
      content: '确认营收平台已换表吗?',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定');
          wx.showLoading({
            title: '勿离开本页面,预计需要30秒...',
          })
          that.handleSendE0()
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  handleOk:function (psn){
    const that=this
    console.log('用户点击确定');
    let data=that.data
    let sendData={
      number:data.number,
      address:data.address,
      latitude:data.latitude,
      longitude:data.longitude,
      remark:data.remark,
      concentrator_images: data.concentratorPicArr,
      "config": {
        // "platform": data.concentrator_detail.config.platform,
        ...data.concentrator_detail.config,
        "meter_config": {}
      }
    }
    for(let i=1;i<=8;i++){
      if(data[`port${i}`]){
        if(data[`port${i}`].length===10||data[`port${i}`].length===12){
          sendData.config.meter_config[`port${i}`]={
            meter_number:data[`port${i}`],
            initial_value:data[`port${i}Origin`],
            remark:data[`port${i}Remark`],
            caliber:data.postCaliberArray[Number(data[`post${i}CaliberIndex`])]?data.postCaliberArray[Number(data[`post${i}CaliberIndex`])]:'DN15',
            meter_images:data[`port${i}PicArr`]
          }
        }else{
          util.toastError(`端口${i}水表号必须长度为10/12位`);
          return;
        }
      }

    }
    console.log('sendData',sendData)
    console.log(JSON.stringify(sendData))
    wx.request({
      url: `${config.prefix}/concentrators/${data.concentrator_detail.id}`,
      header: {
        Authorization: `Bearer ${app.globalData.userInfo.token}`
      },
      method: 'PUT',
      data:sendData,
      success: function (res) {
        console.log('get res', res)
        if (res.statusCode === 200) {
          console.log('更新集中器信息成功')
          that.writeLogs(`更新集中器信息成功`, 'green');
          setTimeout(function (){
            // util.toastError(`更新集中器信息成功`);
          },1500)
          if(that.data.type==='add'){
            wx.request({
              url: `${config.prefix}/concentrator_psn`,
              header: {
                Authorization: `Bearer ${app.globalData.userInfo.token}`
              },
              method: 'POST',
              data:{
                items:[{ meter_number:that.data[`port${Number(that.data.port)}`],psn:0}]

              },
              success: function (res) {
                console.log('get res', res)
                if (res.statusCode === 200) {
                  console.log('设置PSN为0成功')
                  that.writeLogs(`设置PSN为0成功`, 'green');
                }else {
                  util.converErrorCodeToMsg(res)
                }
              }
            })
          }
          if(that.data.type==='del'){
            setTimeout(function (){
              that.handleSendE0()
            },10000)

          }

          if(that.data.type==='swap'){
            setTimeout(function (){
              that.handleSend86(that.data.port)
            },30000)
          }

        }else {
          util.converErrorCodeToMsg(res)
        }
      }
    })


  },
  handleOld:function (){
    const that=this
    console.log('this.data[`display_value_{that.data.port}`]',this.data[`display_value_${that.data.port}`])
    if(!(this.data[`display_value_${that.data.port}`].toString())){
      console.log('旧表盘数不能为空')
      util.toastError(`旧表盘数不能为空`);
      return false
    }
    wx.showModal({
      title: '提示',
      content: '确认旧表数据吗?',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定');
          wx.showLoading({
            title: '采集器上线中，预计需要30秒...',
          })
          that.handleSendE0()
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  },

  handleAddMeter:function (){
    const that=this
    if(!this.data[`port${that.data.port}`]){
      console.log('水表号不能为空')
      util.toastError(`水表号不能为空`);
      return false
    }
    if(this.data[`port${that.data.port}`].length===10||this.data[`port${that.data.port}`].length===12){
    }else{
      util.toastError(`水表号必须长度为10/12位`);
      return;
    }
    if(!this.data[`port${that.data.port}Origin`]){
      console.log('表盘数不能为空')
      util.toastError(`表盘数不能为空`);
      return false
    }
    wx.showModal({
      title: '提示',
      content: '确认添加水表吗?',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定');
          wx.showLoading({
            title: '勿离开本页面,预计需要30秒...',
          })
          that.handleSendE6(`0${that.data.port}`)
          // wx.navigateBack({
          //   delta: 1
          // })

        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  },
  handleDelMeter:function (){
    const that=this
    wx.showModal({
      title: '确认删除水表',
      content: '水表上报的历史数据不可恢复',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定');
          wx.showLoading({
            title: '勿离开本页面,预计需要30秒...',
          })
          that.handleSendE6(`0${that.data.port}`)
          // wx.navigateBack({
          //   delta: 1
          // })

        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  },
  handleSyncMeter:function (){
    const that=this
    wx.showModal({
      title: '提示',
      content: '确认机电同步成功？',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定');
          wx.showLoading({
            title: '勿离开本页面,预计需要30秒...',
          })
          that.handleSend85(`${that.data.port}`)
          // wx.navigateBack({
          //   delta: 1
          // })

        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  },
  handleResetMeter:function (){
    const that=this
    console.log('this.data[`pay_value_${that.data.port}`]',this.data[`pay_value_${that.data.port}`])
    // if(!(this.data[`pay_value_${that.data.port}`].toString())){
    //   console.log('请先获取充值水量')
    //   util.toastError(`请先获取充值水量`);
    //   return false
    // }
    wx.showModal({
      title: '提示',
      content: '确认重置水表？',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定');
          // that.handleSend86(that.data.port)
          wx.showLoading({
            title: '勿离开本页面,预计需要2分钟...',
          })
          that.handleSendE0();
          // setTimeout(function (){
          //   that.handleSendEB()
          // },5000)



          // wx.navigateBack({
          //   delta: 1
          // })

        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  },
  handleNew:function (){
    const that=this
    if(!this.data[`port${that.data.port}`]){
      console.log('水表号不能为空')
      util.toastError(`水表号不能为空`);
      return false
    }
    if(this.data[`port${that.data.port}`].length===10||this.data[`port${that.data.port}`].length===12){
    }else{
      util.toastError(`水表号必须长度为10/12位`);
      return;
    }
    if(!this.data[`port${that.data.port}Origin`]){
      console.log('表盘数不能为空')
      util.toastError(`表盘数不能为空`);
      return false
    }
    wx.request({
      url: `${config.prefix}/concentrators`,
      header: {
        Authorization: `Bearer ${app.globalData.userInfo.token}`
      },
      method: 'GET',
      data: {
        meter_number: this.data[`port${that.data.port}`]
      },
      success: function (res) {
        if (res.statusCode === 200) {
          console.log('获取成功');
          if (res.data.data.length === 1) {
            util.toastError(`该水表已存在于集中器中`)
          } else {
            wx.showModal({
              title: '提示',
              content: '确认换表吗?',
              success(res) {
                if (res.confirm) {
                  console.log('用户点击确定');
                  wx.showLoading({
                    title: '勿离开本页面,预计需要3分钟...',
                  })
                  that.handleSendE6(`0${that.data.port}`)
                  // wx.navigateBack({
                  //   delta: 1
                  // })

                } else if (res.cancel) {
                  console.log('用户点击取消')
                }
              }
            })
          }
        } else {
          util.converErrorCodeToMsg(res)
        }

      }
    })


  },

  gotoCamera: function (e) {
    const that=this
    const ds = e.currentTarget.dataset
    console.log('ds', ds)
    if(ds.port){
      wx.navigateTo({
        url: `/pages/camera/camera?port=${ds.port}&number=${that.data.number}&address=${that.data.address}`
      })
    }else{
      wx.navigateTo({
        url: `/pages/camera/camera?number=${that.data.number}&address=${that.data.address}`
      })
    }

  },
  picPrew: function (e) {
    const ds = e.currentTarget.dataset
    console.log('ds', ds)
    if(ds.port){
      wx.previewImage({
        urls: this.data[`port${ds.port}PicArr`],
        current: ds.item
      })
    }else{
      wx.previewImage({
        urls: this.data.concentratorPicArr,
        current: ds.item
      })
    }

  },
  changeValue: function (e) {
    console.log('ds', e.currentTarget.dataset.item)
    console.log('value', e.detail.value)
    const item = e.currentTarget.dataset.item
    const name = e.currentTarget.dataset.name
    if(name==='port'){
      this.setData({
        [`port${item}`]: e.detail.value
      })
    }else if(name==='portOrigin'){
      this.setData({
        [`port${item}Origin`]: e.detail.value
      })
    }else if(name==='portOld'){
      this.setData({
        [`portOld${item}`]: e.detail.value
      })
    }else if(name==='portOldOrigin'){
      this.setData({
        [`port${item}OldOrigin`]: e.detail.value
      })
    }else if(name==='portRemark'){
      this.setData({
        [`port${item}Remark`]: e.detail.value
      })
    }else if(name==='display_value'){
      this.setData({
        [`display_value_${item}`]: e.detail.value
      })
    }else if(name==='initial_value'){
      this.setData({
        [`initial_value_${item}`]: e.detail.value
      })
    }

  },
  scanPort: function (e) {
    console.log('ds', e.currentTarget.dataset.item)

    const ds = e.currentTarget.dataset.item
    const type = e.currentTarget.dataset.type
    const that = this;
    wx.scanCode({
      scanType: 'barCode',
      success(res) {
        console.log(res)
        // if(JSON.parse(res.result).name){
        //   that.setData({
        //     scanRes:JSON.parse(res.result)
        //   })
        // }else{
        //   util.toastError('二维码内容错误');
        // }
        if(res.result.length!==10&&res.result.length!==12){
          wx.showToast({
            title: `水表号位数不对`,
            icon: 'error'
          })
          return false
        }
        for(let i=0;i<8;i++){
          if(res.result===that.data[`port${i+1}`]){
            wx.showToast({
              title: `端口${i+1}已存在表号`,
              icon: 'error'
            })
            return false
          }
        }
        if(type==='newPort'){
          that.setData({
            [`newPort${ds}`]: res.result
          })
        }else{
          that.setData({
            [`port${ds}`]: res.result
          })
        }



      }
    })
  },
  // bindmarkertap: function () {
  //   wx.openLocation({
  //     latitude: Number(this.data.latitude), // 纬度，范围为-90~90，负数表示南纬
  //     longitude: Number(this.data.longitude), // 经度，范围为-180~180，负数表示西经
  //     scale: 14, // 缩放比例
  //   })
  // },
  /**
   * 选择位置信息
   */
  bindmarkertap: function () {
    if(this.data.editable){
      if(this.data.longitude){
        wx.chooseLocation({
          latitude: Number(this.data.latitude),
          longitude: Number(this.data.longitude),
          success: res => {
            console.log(res)
            this.setData({
              address: res.name,
              latitude: res.latitude,
              longitude: res.longitude,
              markers: [{
                id: 1,
                latitude: res.latitude,
                longitude: res.longitude,
                width: '30', // 标记点图标宽度
                height: '60' // 标记点图标高度
              }],
            })
          },
          fail: err => {
            console.log(err)
          }
        })
      }else{
        wx.chooseLocation({
          success: res => {
            console.log(res)
            this.setData({
              address: res.name,
              latitude: res.latitude,
              longitude: res.longitude,
              markers: [{
                id: 1,
                latitude: res.latitude,
                longitude: res.longitude,
                width: '30', // 标记点图标宽度
                height: '60' // 标记点图标高度
              }],
            })
          },
          fail: err => {
            console.log(err)
          }
        })
      }
    }else{
        wx.openLocation({
          latitude: Number(this.data.latitude), // 纬度，范围为-90~90，负数表示南纬
          longitude: Number(this.data.longitude), // 经度，范围为-180~180，负数表示西经
          scale: 14, // 缩放比例
        })
    }



  },


  fetConctrator: function (department) {
    const that = this;

    wx.request({
      url: `${config.prefix}/concentrators`,
      header: {
        Authorization: `Bearer ${app.globalData.userInfo.token}`
      },
      method: 'GET',
      data: {
        number: that.data.number
      },
      success: function (res) {
        console.log('get res', res)
        if (res.statusCode === 200) {
          if( res.data.data.length===1){
            let data={
              ...res.data.data[0],
              platform:res.data.data[0].config.platform,
              meter_count:res.data.data[0].config.meter_config?Object.keys(res.data.data[0].config.meter_config).length:'',
              version:(res.data.data[0].concentrator_info&&res.data.data[0].concentrator_info.main_software_version)?`${res.data.data[0].concentrator_info.main_software_version}.${res.data.data[0].concentrator_info.sub_software_version}`:''
            }

            console.log('data',data)
            that.setData({
              concentrator_detail:data,
              imei: data.imei,
              id: data.id,
              concentratorPicArr:data.concentrator_images,
              address:data.address,
              remark:data.remark,
              latitude:data.latitude,
              longitude:data.longitude,
              markers: [{
                id: 1,
                latitude: data.latitude,
                longitude: data.longitude,
                width: '30', // 标记点图标宽度
                height: '60' // 标记点图标高度
              }],
            })

            let meter_config=data.config.meter_config
            if(meter_config){
              console.log('meter_config',meter_config)
              for(let i in meter_config){
                let item=meter_config[i];
                let index=i.substr(4,1)
                that.setData({
                  [`port${index}`]: (that.data.type==='swap'&&index===that.data.port)?'':item.meter_number,
                  [`port${index}Remark`]:(that.data.type==='swap'&&index===that.data.port)?'':item.remark,
                  [`port${index}Origin`]:(that.data.type==='swap'&&index===that.data.port)?'':item.initial_value,
                  [`port${index}Caliber`]:item.caliber,
                  [`post${index}CaliberIndex`]:that.data.postCaliberArray.findIndex(function (o){
                    return o===item.caliber
                  }),

                  [`port${index}PicArr`]:(that.data.type==='swap'&&index===that.data.port)?[]:item.meter_images,

                },function (){
                  console.log(that.data)
                })

              }

            }

          }


        }
      }
    })
  },
  editConctrator: function (init) {
    const that = this;
    const concentrator_detail = this.data.concentrator_detail;
    let sendData = {
      ...concentrator_detail,
      config:{
        ...concentrator_detail.config,
        meter_config:{
          ...concentrator_detail.config.meter_config,
          [`port${that.data.port}`]:{
            ...concentrator_detail.config.meter_config[`port${that.data.port}`],
            initial_value:that.data[`initial_value_${that.data.port}`]
          }
        }
      }
    };
    wx.request({
      url: `${config.prefix}/concentrators/${concentrator_detail.id}`,
      header: {
        Authorization: `Bearer ${app.globalData.userInfo.token}`
      },
      method: 'PUT',
      data: sendData,
      success: function (res) {
        console.log('get res', res)
        if (res.statusCode === 200) {
          that.writeLogs('修改系统集中器水表底数成功', 'green')

        } else {
          util.converErrorCodeToMsg(res)
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // this.getRealData();
  },
  changeActive: function (e) {
    console.log(e.currentTarget.dataset.item)
    this.setData({
      navbarActiveIndex: e.currentTarget.dataset.item
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    console.log('list detail onHide')

    // if (this.timer) {
    //   clearTimeout(this.timer)
    // }

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    console.log('list detail onUnload')
    this.stopBluetoothDevicesDiscovery()
    EBOriginData=''
    if (this.timer) {
      clearTimeout(this.timer)
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  // onPullDownRefresh: function() {
  //   console.log('onPullDownRefresh')
  //   this.getInfo()
  // },

  /**
   * 页面上拉触底事件的处理函数
   */
  // onReachBottom: function() {

  // },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function() {

  // }
})